package ar.com.sebasoft.rembrandt;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.holoeverywhere.widget.GridView;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import ar.com.sebasoft.rembrandt.adapter.FotoAdapter;
import ar.com.sebasoft.rembrandt.model.Foto;
import ar.com.sebasoft.rembrandt.util.StringUtil;
import ar.com.sebasoft.rembrandt.util.SystemHelper;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;

/**
 * A fragment representing a single Gallery detail screen. This fragment is
 * either contained in a {@link GalleryListActivity} in two-pane mode (on
 * tablets) or a {@link GalleryDetailActivity} on handsets.
 */
public class GalleryDetailFragment extends SherlockFragment implements OnLoadCompleteListener<Cursor>, OnItemClickListener {
	private static final String JOKER_STRING = "%";

	/**
	 * The fragment argument representing the item ID that this fragment
	 * represents.
	 */
	public static final String ARG_ALBUM_ID = "album_id";

	private static final String EMPTY_STRING = "";

	private int sortOrder = 0; // 0 default / 1 title / 2 date

	private boolean sortOrient = true; // true ASC / false DESC

	/**
	 * The dummy content this fragment is presenting.
	 */
	private String mAlbumString;

	private FotoAdapter mAdapter;

	private GridView mFotoGrid;

	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public GalleryDetailFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (this.getArguments().containsKey(ARG_ALBUM_ID)) {
			this.mAlbumString = this.getArguments().getString(ARG_ALBUM_ID);
		}

		this.setHasOptionsMenu(true);

		this.cargarDiapositivas(this.obtenerPathDeAlbum());
	}

	private String obtenerPathDeAlbum() {
		String res = null;

		if (this.mAlbumString.indexOf("|") != -1) {
			String[] partes = this.mAlbumString.split("\\|");
			if (partes.length > 1) {
				res = partes[1].trim();
			}
		}

		return res;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_gallery_detail, container, false);

		return rootView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_album, menu);
	}

	private void recargarImagenes() {
		this.cargarDiapositivas(this.obtenerPathDeAlbum());
		this.mAdapter.clear();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
			case R.id.mnu_itm_sort_title:
				if (item.isChecked()) {
					this.sortOrient = !this.sortOrient;
				} else {
					this.sortOrient = true;
					item.setChecked(true);
				}
				this.sortOrder = 1;
				this.recargarImagenes();
				return true;
			case R.id.mnu_itm_sort_date:
				if (item.isChecked()) {
					this.sortOrient = !this.sortOrient;
				} else {
					this.sortOrient = true;
					item.setChecked(true);
				}
				this.sortOrder = 2;
				this.recargarImagenes();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		AQuery aq = new AQuery(view);

		this.mAdapter = new FotoAdapter(this.getActivity(), new ArrayList<Foto>());

		this.mFotoGrid = (GridView) aq.id(R.id.photoGallery).getGridView();
		this.mFotoGrid.setAdapter(this.mAdapter);
		this.mFotoGrid.setOnItemClickListener(this);
	}

	private void cargarDiapositivas(String path) {
		if (path != null) {
			Log.d(SystemHelper.APP_TAG, "CARGANDO PATH=" + path);
			// Donde se almacenan las imagenes
			Uri uriExt = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			Uri uriInt = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
			// Las columnas que queremos
			String[] projection = { BaseColumns._ID, MediaColumns.DATA, ImageColumns.DATE_TAKEN, MediaColumns.DATE_ADDED, MediaColumns.TITLE, MediaColumns.DISPLAY_NAME, ImageColumns.DESCRIPTION };
			// Solo queremos las miniaturas
			String selection = MediaColumns.DATA + " LIKE ?";
			String ordering = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
			switch (this.sortOrder) {
				case 1:
					ordering = MediaColumns.TITLE;
					break;
				case 2:
					ordering = ImageColumns.DATE_TAKEN;
					break;
				default:
					ordering = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
					break;
			}
			String orient = "DESC";
			if (this.sortOrient) {
				orient = "ASC";
			}
			CursorLoader cLoaderExt = new CursorLoader(this.getActivity(), uriExt, projection, selection, new String[] { path + JOKER_STRING }, String.format("UPPER(%s) %s", ordering, orient));
			cLoaderExt.registerListener(0, this);
			CursorLoader cLoaderInt = new CursorLoader(this.getActivity(), uriInt, projection, selection, new String[] { path + JOKER_STRING }, ordering);
			cLoaderInt.registerListener(0, this);
			cLoaderExt.startLoading();
			cLoaderInt.startLoading();
		} else {
			SystemHelper.msjShortToast(R.string.err_no_path);
		}
	}

	@Override
	public void onLoadComplete(Loader<Cursor> cLoader, Cursor cursor) {
		AQuery aq = new AQuery(this.getView());
		TextView txtEmpty = aq.id(R.id.emptyGrid).text(R.string.msg_loading_photos).getTextView();

		if ((cursor != null) && (cursor.getCount() > 0)) {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				int col_idx_id = cursor.getColumnIndexOrThrow(BaseColumns._ID);
				int col_idx_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
				int col_idx_date_taken = cursor.getColumnIndexOrThrow(ImageColumns.DATE_TAKEN);
				int col_idx_date_added = cursor.getColumnIndexOrThrow(MediaColumns.DATE_ADDED);
				int col_idx_title = cursor.getColumnIndexOrThrow(MediaColumns.TITLE);
				int col_idx_display = cursor.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
				int col_idx_desc = cursor.getColumnIndexOrThrow(ImageColumns.DESCRIPTION);

				long fechaLong = -1;
				Date fecha = null;
				String titolo = null;

				// ** RESUELVO DATE **
				try {
					fechaLong = cursor.getLong(col_idx_date_taken);
					Log.d(SystemHelper.APP_TAG, "Using Date Taken for pic ID: " + cursor.getLong(col_idx_id));
				} catch (Exception e) {
					Log.d(SystemHelper.APP_TAG, "No Date Taken for pic ID: " + cursor.getLong(col_idx_id));
				}
				if (fechaLong < 0) {
					try {
						fechaLong = cursor.getLong(col_idx_date_added);
						Log.d(SystemHelper.APP_TAG, "Using Date Added for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Date Added for pic ID: " + cursor.getLong(col_idx_id));
					}
				}
				if (fechaLong > 0) {
					fecha = new Date(fechaLong);
				}

				// ** RESUELVO TITULO **
				try {
					titolo = cursor.getString(col_idx_title);
					Log.d(SystemHelper.APP_TAG, "Using Title for pic ID: " + cursor.getLong(col_idx_id));
				} catch (Exception e) {
					Log.d(SystemHelper.APP_TAG, "No Title for pic ID: " + cursor.getLong(col_idx_id));
				}
				if ((titolo == null) || titolo.trim().equals(EMPTY_STRING)) {
					try {
						titolo = cursor.getString(col_idx_display);
						Log.d(SystemHelper.APP_TAG, "Using Display Name for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Display Name for pic ID: " + cursor.getLong(col_idx_id));
					}
				}
				if ((titolo == null) || titolo.trim().equals(EMPTY_STRING)) {
					try {
						titolo = cursor.getString(col_idx_desc);
						Log.d(SystemHelper.APP_TAG, "Using Description for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Description Name for pic ID: " + cursor.getLong(col_idx_id));
					}
				}

				this.agregarThumbnailALista(cursor.getLong(col_idx_id), cursor.getString(col_idx_data), fecha, titolo);
				cursor.moveToNext();
			}
		} else {
			txtEmpty.setText(R.string.msg_no_pictures);
		}
		this.mFotoGrid.setEmptyView(txtEmpty);
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		this.mAdapter.clearCache();
	}

	private void agregarThumbnailALista(long id, String path, Date fecha, String titulo) {
		Log.d(SystemHelper.APP_TAG, "ID=" + id + " PATH=" + path + " TITULO=" + titulo);
		this.mAdapter.add(new Foto(id, path, titulo, fecha));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Object tag = view.getTag();

		if (tag != null) {
			Foto estaFoto = (Foto) tag;
			Intent itnt = new Intent(this.getActivity(), PresentationActivity.class);
			Bundle bolsillo = new Bundle();

			List<Foto> listaFoto = this.mAdapter.getmList();
			if (listaFoto.size() < 300) {
				if (listaFoto.size() == 1) {
					bolsillo.putString(PresentationActivity.PARAM_PHOTO, estaFoto.getPath());
					bolsillo.putLong(PresentationActivity.PARAM_PHOTO_ID, estaFoto.getImgID());
					if (estaFoto.getTitulo() != null) {
						bolsillo.putString(PresentationActivity.PARAM_TITLE, estaFoto.getTitulo());
					}
					if (estaFoto.getFecha() != null) {
						bolsillo.putLong(PresentationActivity.PARAM_DATE, estaFoto.getFecha().getTime());
					}

				} else if (listaFoto.size() > 0) {
					ArrayList<String> listaFotoString = new ArrayList<String>();
					for (Foto foto : listaFoto) {
						listaFotoString.add(foto.toString());
					}
					bolsillo.putStringArrayList(PresentationActivity.PARAM_GALLERY, listaFotoString);
					bolsillo.putLong(PresentationActivity.PARAM_PHOTO_ID, estaFoto.getImgID());
				}
			} else {
				bolsillo.putString(PresentationActivity.PARAM_PATH, StringUtil.getAlbumPath(estaFoto.getPath()));
				bolsillo.putLong(PresentationActivity.PARAM_PHOTO_ID, estaFoto.getImgID());
			}

			itnt.putExtras(bolsillo);
			this.startActivity(itnt);
		} else {
			SystemHelper.msjShortToast(R.string.msg_no_pictures);
		}
	}
}